package org.easymodelers.gmf.creator.impl;

import java.io.IOException;

import org.easymodelers.gmf.creator.GmfToolCreator;
import org.easymodelers.gmf.utils.GmfModelsUtils;
import org.easymodelers.gmf.utils.ModelCreatorCallback;
import org.easymodelers.modeler.data.Element;
import org.easymodelers.modeler.data.Modeler;
import org.eclipse.gmf.tooldef.CreationTool;
import org.eclipse.gmf.tooldef.GMFToolFactory;
import org.eclipse.gmf.tooldef.Palette;
import org.eclipse.gmf.tooldef.ToolGroup;
import org.eclipse.gmf.tooldef.ToolRegistry;

public class DefaultGmfToolCreator implements GmfToolCreator {

	private GMFToolFactory getToolFactory() {
		return GMFToolFactory.eINSTANCE;
	}
	
	public void createGmfTool(String modelPath, final Modeler modeler) throws IOException {
		GmfModelsUtils.createGmfModel(modelPath, new ModelCreatorCallback<ToolRegistry>() {
			public ToolRegistry createModelRootElement() throws IOException {
				GMFToolFactory toolFactory = getToolFactory();
				ToolRegistry toolRegistry = toolFactory.createToolRegistry();
				Palette palette = toolFactory.createPalette();
				toolRegistry.setPalette(palette);
				ToolGroup toolGroup = toolFactory.createToolGroup();
				toolGroup.setTitle("Elements");
				palette.getTools().add(toolGroup);

				for (Element element : modeler.getElements()) {
					handleElement(element, toolGroup);
				}
				
				return toolRegistry;
			}
		});
	}

	private void handleElement(Element element, ToolGroup toolGroup) {
		GMFToolFactory toolFactory = getToolFactory();

		CreationTool elementCreationTool = toolFactory.createCreationTool();
		elementCreationTool.setTitle("Create "+element.getName());
		toolGroup.getTools().add(elementCreationTool);
	}
}
